<template>
  <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
    <el-tab-pane label="存放中" name="first">
      <layout-card ref="storeLayoutCardRef" :filters="goodsRegStoreOptions" @update:modelValue="handlerUpdateModelValue" headline="捡拾物品公示" @search-change="searchChange"
        @search-reset="searchReset">
        <template #action>
          <el-button type="primary" @click="handleApplyStorage(2)">批量接收</el-button>
          <el-button type="primary" @click="handleApplyStorage(1)">申请入库</el-button>
          <el-button type="primary" @click="handleCreate">新增</el-button>
        </template>
        <div class="table-common">
          <div class="goods">
            <div class="goods_content" v-for="(item, index) in tableData" :key="index" @click="goodsClick(item)">
              <img :src="item['goodsFiles'] ? item['goodsFiles'][0] != null ? item['goodsFiles'][0]['resourceAddress'] : '' : image.noImg" class="image" />
              <div class="message">
                <div class="message_content">
                  <div class="type" :title="item['goodsName']">{{ item['goodsName']}}</div>
                  <div class="terminal">{{ item['taskProcess'] }}</div>
                </div>
                <div class="message_content">
                  <div class="headline">物品类型：</div>
                  <div class="headline_content">{{ getGoodsTypeName(item['goodsType']) }}</div>
                </div>
                <div class="message_content" >
                  <div class="headline">捡拾日期：</div>
                  <div class="headline_content">{{ dayjs(item['pickUpTime']).format('YYYY-MM-DD') }}</div>
                </div>
                <div class="message_content" >
                  <div class="headline">捡拾地：</div>
                  <div class="headline_content pickUpPlace" :title="item['pickUpPlace']">{{ item['pickUpPlace'] }}</div>
                </div>
                <div class="message_content">
                  <div class="headline">物品编号：</div>
                  <div class="headline_content">{{ item['goodsCode'] }}</div>
                </div>
              </div>
              <div
                :class="item['expireCountDown']=== null ? 'hidden_overdue' : (item['expireCountDown'] === 0 ? 'red_overdue' : 'green_overdue')">
                {{ item['expireCountDown'] != null ? (item['expireCountDown'] === 0 ? '1小时内过期' : item['expireCountDown'] + '小时后过期') : ''}}
              </div>
            </div>
          </div>
          <div>
            <TablePagination :small="false" :pagination="pager" @current-change="currentChange"
              @size-change="sizeChange" />
          </div>
        </div>
      </layout-card>
    </el-tab-pane>
    <el-tab-pane label="已归还" name="second">
      <layout-card ref="returnLayoutCardRef" :filters="goodsRegReturnOptions" headline="捡拾物品公示" @search-change="searchChange"
        @search-reset="searchReset">
        <div class="table-common">
          <div class="goods">
            <div class="return_goods_content" v-for="(item, index) in tableData" :key="index" @click="goodsClick(item)">
              <img :src="item['goodsFiles'] ? item['goodsFiles'][0] != null ? item['goodsFiles'][0]['resourceAddress'] : '' : image.noImg" class="image" />
              <div class="message">
                <div class="message_content">
                  <div class="type" :title="item['goodsName']">{{ item['goodsName'] }}</div>
                  <div class="terminal">{{ item['taskProcess'] }}</div>
                </div>
                <div class="message_content">
                  <div class="headline">物品类型：</div>
                  <div class="headline_content">{{ getGoodsTypeName(item['goodsType']) }}</div>
                </div>
                <div class="message_content">
                  <div class="headline">捡拾日期：</div>
                  <div class="headline_content">{{ dayjs(item['pickUpTime']).format('YYYY-MM-DD') }}</div>
                </div>
                <div class="message_content">
                  <div class="headline">捡拾地：</div>
                  <div class="headline_content pickUpPlace" :title="item['pickUpPlace']">{{ item['pickUpPlace'] }}</div>
                </div>
                <div class="message_content">
                  <div class="headline">物品编号：</div>
                  <div class="headline_content">{{ item['goodsCode'] }}</div>
                </div>
              </div>
              <img :src="image.received" class="received-img">
            </div>
          </div>
          <div>
            <TablePagination :small="false" :pagination="pager" @current-change="currentChange"
              @size-change="sizeChange" />
          </div>
        </div>
      </layout-card>
    </el-tab-pane>
  </el-tabs>

  <!-- 新增弹窗 -->
  <Add :visible="addDialogVisible" :goodsType="goodsTypeDatas" @cancel="Cancel" @submit="Submit" />
  <!-- 申请入库弹窗、批量接收 -->
  <ApplyStoreage :visible="applyStoreDialogVisible" :state="state" @cancel="Cancel" @submit="Submit"/>
  <!-- 存放中-详情 -->
  <StoreDetail :visible="centerDialogVisible" :info="storeDetail" @show="showStoreDetail" @cancel="Cancel" @submit="Submit"/>
  <!-- 已归还-详情 -->
  <ReturnDetail :visible="returnDialogVisible" :info="storeDetail" @cancel="Cancel" @submit="Submit"/>
</template>

<script lang="ts" setup>
import { ref, reactive, onBeforeMount, watch, computed } from 'vue'
import { useStore } from 'vuex'
import LayoutCard from '@/components/LayoutCard/index.vue'
import type { TabsPaneContext } from 'element-plus'
import editDialog from '@/components/editDialog/index.vue'
import TablePagination from '@/components/TablePagination/index.vue'
import { image } from '@/assets/index'
import { goodsRegStoreOptions, goodsRegReturnOptions } from './config/filters'
import Add from './add.vue'
import ApplyStoreage from './applyStorage.vue'
import StoreDetail from './detail.vue'
import ReturnDetail from './returnDetail.vue'
import { goodsReg } from '@/api/lose/goodsReg'
import dayjs from 'dayjs'
import { getGoodsTypeName } from '@/utils/common'

// 标题名
const activeName = ref('first')
// 详情弹窗是否打开
const centerDialogVisible = ref(false)
// 领取弹窗是否打开
const receiveDialogVisible = ref(false)
// 新增弹窗是否打开
const addDialogVisible = ref(false)
// 申请入库弹窗是否打开
const applyStoreDialogVisible = ref(false)
const state = ref(1)
// 已归还详情弹窗
const returnDialogVisible = ref(false)
// 弹窗标题
const tilte = ref('新增')
const loading = ref(false)
const tableData = ref([])
const dialogWidth = ref('760px')
const storeDetail = ref({})
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const search = ref<FilterDataType>({})
const store = useStore()
const paneName = ref<any>('first')
const storeLayoutCardRef = ref()
const returnLayoutCardRef = ref()
const formatSeconds = (seconds: number) => {
  const hour = 60 * 60
  const hourStr = dayjs().hour(~~(seconds / hour)).format('H')
  return hourStr
}
/**
 * 标签页点击切换
*/
const handleClick = (tab: TabsPaneContext, event: Event) => {
  paneName.value = tab.paneName
  search.value = {}
  if (tab.paneName === 'second') {
    // search.value.isPickUp = '1'
    search.value.taskProcess = '已领取'
  } else {
    delete search.value.isPickUp
    search.value.taskProcess = '未接收,已接收,入库审批,入库审批驳回,入库申请驳回,已入库,出库审批,出库审批驳回,已出库'
  }
  let searchForm: any = {}
  goodsRegStoreOptions.value.forEach(v => {
    searchForm[v.prop] = v.defaultValue
  })
  storeLayoutCardRef.value.setFieldsValue(searchForm)
  searchForm = {}
  goodsRegReturnOptions.value.forEach(v => {
    searchForm[v.prop] = v.defaultValue
  })
  returnLayoutCardRef.value.setFieldsValue(searchForm)
  tableData.value = []
  pager.currentPage = 1
  pager.total = 0
  pager.pageSize = 10
  getData()
}

/**
 * 申请入库、批量接收
 */
const handleApplyStorage = (val: number) => {
  applyStoreDialogVisible.value = true
  state.value = val
}

/**
 * 点击新增方法
 */
const handleCreate = () => {
  addDialogVisible.value = true
}

/**
 * 弹窗点击取消
 */
const Cancel = () => {
  loading.value = false
  centerDialogVisible.value = false
  returnDialogVisible.value = false
  receiveDialogVisible.value = false
  addDialogVisible.value = false
  applyStoreDialogVisible.value = false
}

/**
 * 弹窗点击确认
 */
const Submit = () => {
  pager.currentPage = 1
  pager.total = 0
  pager.pageSize = 10
  loading.value = false
  returnDialogVisible.value = false
  centerDialogVisible.value = false
  receiveDialogVisible.value = false
  addDialogVisible.value = false
  applyStoreDialogVisible.value = false
  getData()
}

/**
 * 卡片点击事件
 */
const goodsClick = (item: any) => {
  if (paneName.value === 'second') {
    returnDialogVisible.value = true
  } else {
    centerDialogVisible.value = true
  }
  storeDetail.value = {
    regId: item.regId.toString(),
    taskId: item.taskId,
    taskProcess: item.taskProcess
  }
}

const showStoreDetail = () => {
  centerDialogVisible.value = true
}

// 分页
const sizeChange = (size: number) => {
  pager.pageSize = size
  getData()
}
const currentChange = (value: number) => {
  pager.currentPage = value
  getData()
}
const getData = () => {
  loading.value = true
  if (Array.isArray(search.value.storePosition)) {
    search.value.storePosition.length === 0 ? delete search.value.storePosition : search.value.storePosition = search.value.storePosition.join(',')
  }
  if (Array.isArray(search.value.storeTerminal)) {
    search.value.storeTerminal.length === 0 ? delete search.value.storeTerminal : search.value.storeTerminal = search.value.storeTerminal.join(',')
  }
  if (Array.isArray(search.value.storeTime)) {
    search.value.storeTime.length === 0 ? delete search.value.storeTime : search.value.storeTime = search.value.storeTime.join(',')
  }
  if (Array.isArray(search.value.goodsType)) {
    search.value.goodsType.length === 0 ? delete search.value.goodsType : search.value.goodsType = search.value.goodsType.join(',')
  }
  if (Array.isArray(search.value.startTime)) {
    if (search.value.startTime.length > 0) {
      const date = search.value.startTime
      search.value.startTime = date[0] + ' 00:00:00'
      search.value.endTime = date[1] + ' 23:59:59'
    } else {
      delete search.value.startTime
    }
  }

  if (paneName.value === 'first') {
    search.value.taskProcess = '未接收,已接收,入库审批,入库审批驳回,入库申请驳回,已入库,出库审批,出库审批驳回,已出库'
  }

  const params = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: { ...search.value, order: [{ column: 'pick_up_time', method: 'asc' }] }
  }
  goodsReg(params).then(res => {
    if (res.data) {
      loading.value = false
      // @ts-ignore
      tableData.value = res.data.list
      pager.total = res.data.total
    }
  }).catch(() => {
    loading.value = false
  })
}

/**
 * 更新modelValue
 */
const handlerUpdateModelValue = (data: FilterDataType) => {
  console.log('data', data)
}
/**
 * 点击查询
 */
const searchChange = (data: FilterDataType) => {
  search.value = data
  if (paneName.value === 'second') {
    // 已归还查询
    search.value.isPickUp = '1'
    search.value.taskProcess = '已领取'
  } else {
    delete search.value.isPickUp
    search.value.taskProcess = '未接收,已接收,入库审批,入库审批驳回,入库申请驳回,已入库,出库审批,出库审批驳回,已出库'
  }
  getData()
}

/**
 * 点击重置
 * @param data 数据
 */
const searchReset = (data: FilterDataType) => {
  search.value = data
  pager.currentPage = 1
  pager.pageSize = 10
  if (paneName.value === 'second') {
    // 已归还查询
    search.value.isPickUp = '1'
    search.value.taskProcess = '已领取'
  } else {
    delete search.value.isPickUp
    search.value.taskProcess = '未接收,已接收,入库审批,入库审批驳回,入库申请驳回,已入库,出库审批,出库审批驳回,已出库'
  }
  getData()
}

const loadTerminal = async () => {
  store.dispatch('terminal/getDict')
}
const goodsTypeDatas = computed(() => store.state.goodsType.typeList)
const loadGoodsType = () => {
  store.dispatch('goodsType/getGoodsType')
}

const loadDepositPlace = () => {
  store.dispatch('depositPlace/getDict')
}

watch(
  () => store.state.terminal.data, () => {
    const options: Array<any> = []
    store.state.terminal.data.forEach((ele: any) => {
      options.push(ele)
    })
    goodsRegStoreOptions.value[5].inputProps.options = options
    goodsRegReturnOptions.value[5].inputProps.options = options
  }
)
watch(
  () => store.state.goodsType.typeList,
  () => {
    const options: Array<any> = []
    store.state.goodsType.typeList.forEach((ele: any) => {
      options.push({ label: ele.goodsType, value: ele.typeId })
    })
    goodsRegStoreOptions.value[7].inputProps.options = options
    goodsRegReturnOptions.value[6].inputProps.options = options
  }
)
watch(
  () => store.state.depositPlace.data,
  () => {
    const options: Array<any> = []
    store.state.depositPlace.data.forEach((ele: any) => {
      options.push({ label: ele.name, value: ele.key })
    })
    goodsRegStoreOptions.value[4].inputProps.options = options
    goodsRegReturnOptions.value[4].inputProps.options = options
  }
)
const initData = () => {
  // 获取航站楼
  loadTerminal()
  // 获取物品类型
  loadGoodsType()
  // 获取存放地
  loadDepositPlace()
  getData()
}

onBeforeMount(initData)
</script>

<style lang="less" scoped>
  @import url("./index.less");
</style>
